package com.yehun.admin.controller;

import com.yehun.model.UserLoginModel;
import com.yehun.shiro.AdminToken;
import com.yehun.shiro.ShiroUserType;
import com.yehun.utils.MD5Utils;
import com.yehun.utils.RequestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

@Controller
@RequestMapping(value = "account")
public class AccountController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(AccountController.class);

    @RequestMapping(value = "login", name = "登录")
    public String login(Model model) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:info";
        }
        model.addAttribute("user", new UserLoginModel());
        return "account/login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST, name = "登录提交")
    public ModelAndView login(@Valid @ModelAttribute("user") UserLoginModel userLogin, BindingResult bindingResult) {
        ModelAndView view = new ModelAndView("account/login");
        logger.info("AccountController.loginPost, user={}", userLogin.toString());
        if (!bindingResult.hasErrors()) {
            logger.info("AccountController.login, user valid success");
            Subject subject = SecurityUtils.getSubject();
            AdminToken token = new AdminToken(userLogin.getUsername(), MD5Utils.md5(userLogin.getPassword()));
            token.setType(ShiroUserType.ADMIN);
            token.setRememberMe(false);
            token.setHost(RequestUtils.getIp());
            try {
                subject.login(token);
                if (subject.isAuthenticated()) {
                    view.setViewName("redirect:/admin/main");
                    return view;
                }
            } catch (UnknownAccountException e) {
                logger.debug("账号不存在：", e);
                view.addObject("message", "账号不存在");
            } catch (DisabledAccountException e) {
                logger.debug("账号未启用：", e);
                view.addObject("message", "账号未启用");
            } catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                logger.debug("密码错误：", e);
                view.addObject("message", "密码错误");
            } catch (RuntimeException e) {
                logger.debug("未知错误,请联系管理员：", e);
                view.addObject("message", "未知错误,请联系管理员");
            }
        }
        return view;
    }

    @RequestMapping(value = { "logout", "exit" }, name = "退出")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return "redirect:login";
    }

    @RequestMapping(value = "info", name = "用户信息")
    public String info(Model model) {
        model.addAttribute("currentUser", super.getCurrentUser());
        return "account/info";
    }

    @RequestMapping(value = "unauth")
    public String unauth() {
        return "account/unauth";
    }
}
